export function randomData() {
  return Math.round(Math.random() * 500)
}

export function tooltipPosition(point, params, dom, rect, size) {
  // 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
  // 提示框位置
  var x = 0 // x坐标位置
  var y = 0 // y坐标位置

  // 当前鼠标位置
  var pointX = point[0]
  var pointY = point[1]

  // 外层div大小
  // var viewWidth = size.viewSize[0];
  // var viewHeight = size.viewSize[1];

  // 提示框大小
  var boxWidth = size.contentSize[0]
  var boxHeight = size.contentSize[1]

  // boxWidth > pointX 说明鼠标左边放不下提示框
  if (boxWidth > pointX) {
    x = 5
  } else {
    // 左边放的下
    x = pointX - boxWidth
  }

  // boxHeight > pointY 说明鼠标上边放不下提示框
  if (boxHeight > pointY) {
    y = 5
  } else {
    // 上边放得下
    y = pointY - boxHeight
  }

  return [x, y]
}

export function coppyObj(arr) {
  return arr.map(e => {
    if (typeof e === 'object') {
      return Object.assign({}, e)
    } else {
      return e
    }
  })
}

// 深度克隆
export function deepClone(obj) {
  if (typeof obj !== 'object' && typeof obj !== 'function') {
    return obj // 原始类型直接返回
  }
  var o = Object.prototype.toString.call(obj) === '[object Array]' ? [] : {}
  for (let i in obj) {
    if (obj.hasOwnProperty(i)) {
      o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
    }
  }
  return o
}
// 处理为null的值
export function numberToEmpty(data) {
  for (var index in data) {
    if (data[index] === null) {
      data[index] = undefined;
    }
  }
  return data;
}
// 获取昨天时和跨过去年时
export function getNowFormatDateToYear(d, n) {
  var date = new Date()
  date.setDate(date.getDate() + d)	
  // var seperator1 = seperator || ''
  // var rule1 = rule || 'YYYY-MM-DD'
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()

  var hour = date.getHours()
  var min = date.getMinutes();
  var second = date.getSeconds();

  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
  }
  if (min >= 0 && min <= 9) {
    min = '0' + min
  }
  if (second >= 0 && second <= 9) {
    second = '0' + second
  }

  let currentdate = `${year}-${month}-${strDate} ${hour}:${min}:${second}`
  let laseDdate = `${year - n}-${month}-${strDate} ${hour}:${min}:${second}`
  return [laseDdate, currentdate];
}
// 获取当前时
export function getNowFormatDate() {
  var date = new Date()
  // var seperator1 = seperator || ''
  // var rule1 = rule || 'YYYY-MM-DD'
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()

  var hour = date.getHours()
  var min = date.getMinutes();
  var second = date.getSeconds();

  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
  }
  if (min >= 0 && min <= 9) {
    min = '0' + min
  }
  if (second >= 0 && second <= 9) {
    second = '0' + second
  }

  var currentdate = `${year}-${month}-${strDate} ${hour}:${min}:${second}`
  return currentdate
}

// 获取返回时间中的月份
export function getMonthData(str) {
  if (typeof str !== 'string') {
    return 0
  }

  var formatMonth =
    str.slice(0, 4) +
    '-' +
    str.slice(4, 6) +
    (str.slice(6, 8) && '-' + str.slice(6, 8))
  return new Date(formatMonth).getMonth() + 1
}

export function cutstr(str = '', len = 6) {
  if (!str) {
    return ''
  }
  let result = ''
  let strlen = str.length
  let chrlen = str.replace(/[^\x00-\xff]/g, '**').length
  if (!(typeof str === 'string' && str.constructor === String)) {
    return ''
  }
  if (chrlen <= len) {
    return str
  }
  for (let i = 0, j = 0; i < strlen; i++) {
    let chr = str.charAt(i)
    if (/[\x00-\xff]/.test(chr)) {
      j++ // ascii码为0-255，一个字符就是一个字节的长度
    } else {
      j += 2 // ascii码为0-255 以外，一个字符就是两个字节的长度
    }
    if (j <= len) {
      // 当加上当前字符以后，如果总字节长度小于等于L，则将当前字符真实的+在result后
      result += chr
    } else {
      // 反之则说明result已经是不拆分字符的情况下最接近L的值了，直接返回
      return result + '...'
    }
  }
}
// 多坐标X轴值不对应 进行转换为对应
export function tarnsformChartsData(obj = {}) {
  let xData = []
  let nObj = obj

  // 取最大X轴数据
  for (let key in obj) {
    if (key.includes('X')) {
      xData =
        obj[key] instanceof Array && obj[key].length > xData.length
          ? obj[key]
          : xData
    }
  }

  // 为Y轴补空数据
  for (let key in obj) {
    if (key.includes('X')) {
      let iXdata = obj[key]
      let iYdata = obj[key.replace('X', 'Y')]
      let nYdata = []
      xData.forEach(item => {
        let index = iXdata.indexOf(item)
        nYdata.push(index !== -1 ? iYdata[index] : 0)
      })
      obj[key.replace('X', 'Y')] = nYdata
    }
  }
  nObj.xData = xData
  return nObj
}

// 判断是否IE环境
export function IEVersion() {
  var userAgent = window.navigator.userAgent // 取得浏览器的userAgent字符串
  var isIE =
    userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 // 判断是否IE<11浏览器
  var isEdge = userAgent.indexOf('Edge') > -1 && !isIE // 判断是否IE的Edge浏览器
  var isIE11 =
    userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1
  if (isIE) {
    var reIE = new RegExp('MSIE (\\d+\\.\\d+);')
    reIE.test(userAgent)
    var fIEVersion = parseFloat(RegExp['$1'])
    if (fIEVersion == 7) {
      return 7
    } else if (fIEVersion == 8) {
      return 8
    } else if (fIEVersion == 9) {
      return 9
    } else if (fIEVersion == 10) {
      return 10
    } else {
      return 6 // IE版本<=7
    }
  } else if (isEdge) {
    return 'edge' // edge
  } else if (isIE11) {
    return 11 // IE11
  } else {
    return -1 // 不是ie浏览器
  }
}

// 二次确认modal
export async function confirmRecordOperate(tipMsg = '是否继续确认删除？', titleMsg = '删除属性', btnOkText = '确认删除', btnCancelText = '取消', that, callback) {
  try {
    await that.$confirm(tipMsg, titleMsg, {
      confirmButtonText: btnOkText,
      cancelButtonText: btnCancelText,
      distinguishCancelAndClose: true,
      dangerouslyUseHTMLString: true,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      beforeClose: async (action, instance, done) => {
        switch (action) {
          case 'close':
          case 'cancel':
            done();
            break;
          case 'confirm':
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            setTimeout(() => {
              callback();
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
              }, 300);
            }, 2000);
            break;
        }
      },
      type: 'warning'
    });
  } catch (e) {}
}

// post导出excel
export function postExcelFile(params, url) {
  // params是post请求需要的参数，url是请求url地址
  var form = document.createElement('form');
  form.style.display = 'none';
  form.action = url;
  form.method = 'post';
  document.body.appendChild(form);
  // 动态创建input并给value赋值
  for (var key in params) {
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key;
    input.value = params[key];
    form.appendChild(input);
  }

  form.submit();
  form.remove();
}

export function getNearMonthFormatDate () {
  let date = new Date();
  let seperator = '-';
  let year = date.getFullYear();
  let lastMonth = date.getMonth() + 1;
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  let endFormatDate;
  let startFormatDate;
  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  if (lastMonth >= 1 && lastMonth <= 9) {
    lastMonth = '0' + lastMonth;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate;
  }
  if (lastMonth - 1 === 0) {
    let lastYear = year - 1;
    lastMonth = 12;
    startFormatDate = lastYear + seperator + lastMonth + seperator + strDate;
  } else {
    startFormatDate = year + seperator + lastMonth + seperator + strDate;
  }
  endFormatDate = year + seperator + month + seperator + strDate;
  return [startFormatDate, endFormatDate];
}

// 判断首字母和第六位字母 - 危险品标识
export function checkStr(_putrecNo) {
  if((_putrecNo.substr(0, 1) == 'T' || _putrecNo.substr(0, 1) == 'H')||(_putrecNo.substr(0, 1) == 'L' && _putrecNo.substr(5, 1) == 'B')) {
    return '1';
  } else {
    return '0';
  }
}

export function ifNullToArray(obj) {
  if (obj === null) {
    return [];
  } else {
    return obj;
  }
}

export function getCurrentDate(d){
  var date = new Date();
  date.setDate(date.getDate() + d)	
  //当使用setDate()之后，date对象就发生了改变，所以之后getDate()就能获取到指定的日期
  //这里的num就是你要加的天数，减也可以。
  let year = date.getFullYear()				//年
  let month = date.getMonth() + 1				//月
  let day = date.getDate();					//天数
  if(month >= 1 && month <= 9) {
    month = `0${month}`
  }
  if(day >= 1 && day <= 9) {
    day = `0${day}`
  }
  return `${year}-${month}-${day}`
}

// 几天前或几天后
// export function getAfertDayOrBeforeDate(d) {
//   let currentTime = getCurrentDate(0);
//   let poorTime = getCurrentDate(d);
//   return [currentTime, poorTime];
// }

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function(...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

export function autoPlayUl(dom) {
  var timer = null;
  dom.scrollTop = 0;
  dom.innerHTML += dom.innerHTML;
  function play() {
      clearInterval(timer);
      timer = setInterval(function() {
        dom.scrollTop++;
          if (dom.scrollTop >= dom.scrollHeight / 2) {
            dom.scrollTop = 0;
          }
      }, 100);
  }
  setTimeout(play, 500);
  dom.onmouseover = function() {
      clearInterval(timer)
  };
  dom.onmouseout = play;
}

export function isTimeLengthtoFormat(t, flag) {
  if (flag && t >= 0 && t <= 9) {
    t = '0' + t;
  } else {
    if (t >= 1 && t <= 9) {
      t = '0' + t;
    }
  }
  return t;
}

// 三个月内的范围时间
export function getLast3Month() {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;//0-11表示1-12月
  var day = now.getDate();
  var dateObj = {};
  if (parseInt(month) < 10) {
      month = "0" + month;
  }
  if (parseInt(day) < 10) {
      day = "0" + day;
  }

  dateObj.now = year + '-' + month + '-' + day;

  if (parseInt(month) == 1) {//如果是1月份，则取上一年的10月份
      dateObj.last = (parseInt(year) - 1) + '-10-' + day;
      return dateObj;
  }
  if (parseInt(month) == 2) {//如果是2月份，则取上一年的11月份
      dateObj.last = (parseInt(year) - 1) + '-11-' + day;
      return dateObj;
  }
  if (parseInt(month) == 3) {//如果是3月份，则取上一年的12月份
      dateObj.last = (parseInt(year) - 1) + '-12-' + day;
      return dateObj;
  }

  var preSize = new Date(year, parseInt(month) - 3, 0).getDate();//开始时间所在月的总天数
  if (preSize < parseInt(day)) {  
    // 开始时间所在月的总天数<本月总天数，比如当前是5月30日，在2月中没有30，则取下个月的第一天(3月1日)为开始时间
    let resultMonth = parseInt(month) - 2 < 10 ? ('0' + parseInt(month) - 2) : (parseInt(month) - 2);  
    dateObj.last = year + '-' + resultMonth + '-01';  
    return dateObj;
  }

  if (parseInt(month) <= 10) {
      dateObj.last = year + '-0' + (parseInt(month) - 3) + '-' + day;
      return dateObj;
  } else {
      dateObj.last = year + '-' + (parseInt(month) - 3) + '-' + day;
      return dateObj;
  }

}

// 根据对象属性类型初始化对象
export function resetObjParams (inObj) {
  let obj = {...inObj}
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key] && typeof obj[key] == 'object') {
        obj[key] = Array.isArray(obj[key]) ? [] : {}
      } else {
        obj[key] = '';
      }
    }
  }
  return obj
}

// 复制文本
export function copyText (copytext) {
  const text = document.createElement('input'); // 创建节点
  text.setAttribute('readonly', 'readonly');
  text.value = copytext; // 赋值
  document.body.appendChild(text); // 插入节点
  text.setSelectionRange(0, text.value.length);
  text.select(); // 选中节点
  document.execCommand('copy'); // 执行浏览器复制方法
  if (document.body.removeChild(text)) {
    this.$message({ type: 'success', message: '复制成功' })
  } else {
    this.$message({ type: 'error', message: '复制失败' })
  }
}
